package com.nuanshui.heatedloan.userinfo.service;

import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.UniqueIdGenerator;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.search.facade.util.SearchUtil;
import com.nuanshui.heatedloan.userinfo.constant.LoginAccountType;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserWeixinAccountMapper;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UsersMapper;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.facade.UserStateService;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.ThirdUserService;
import com.nuanshui.heatedloan.userinfo.form.BoundUserForm;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.model.UserInfo;
import com.nuanshui.heatedloan.userinfo.model.UserWeixinOpenId;
import com.nuanshui.heatedloan.userinfo.service.thirdLogin.ThirdUserServiceUtil;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service(ServiceConstant.UserService)
@Transactional(readOnly = true, value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
public class UserServiceImpl extends CommonServiceImpl implements UserService, InitializingBean {

    @Autowired
    private UserAuthServiceImpl userAuthServiceImpl;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private UsersMapper userMapper;

    @Autowired
    private UserStateService userStateService;

    @Autowired
    private PasswordEncoder pwdEncoder;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private UserWeixinAccountMapper userWeixinAccountMapper;

    @Autowired
    private UserTool userTool;

    //@Autowired
    private SearchUtil searchUtil;

    @Override
    public boolean isPwdSet() {
        User user = userMapper.selectByPrimaryKey(userTool.getCurrentUser().getId());
        return user != null && user.getPassword() != null;
    }

    /**
     * 判断用户是否注册
     */
    @Override
    public boolean isRegistered(String loginName) {
        return userMapper.countRegistered(loginName) > 0;
    }


    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public User register(String phone, String password) {
        //String channel =getUserAgent().getChannel();
        String channel = getCurrentChannel();
        // 用户的验证应该放到这里来，否则有安全问题
        User u = userMapper.loadByLoginname(phone);
        if (u != null) {
            if (pwdEncoder.matches(password, u.getPassword())) {
                return u;
            }
            throw new BizException(GlobalErrorCode.UNKNOWN, "用户[" + phone + "]已经注册，请直接登录或者使用其他的用户名注册");
        }
        User user = new User();
        user.setLoginname(phone);
        user.setPhone(phone);
        user.setRecommended(false);
        user.setPassword(pwdEncoder.encode(password));

        //设置默认的用户名
        if (StringUtils.isEmpty(user.getNick())) {
            user.setNick(GlobalParam.USER_DEFAULT_NICK + UniqueIdGenerator.generateRandomNumStr(6));
        }
        //设置默认的个性签名
        if (StringUtils.isEmpty(user.getSignature())) {
            user.setSignature(GlobalParam.USER_DEFAULT_SIGNATURE);
        }
        this.insert(user);

        userAuthServiceImpl.loadUserAuth(user.getId());
        //saveUserQrcode(user.getId());


        userStateService.setUserChannel(user.getId(), channel);


        return user;
    }

    @Override
    public void saveUserQrcode(final String userId) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String qrcode = generateQrcode(userId);
                UserInfo userInfo = new UserInfo();
                userInfo.setId(userId);
                userInfo.setQrcode(qrcode);
                updateUserInfo(userInfo, false);

            }
        });
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public boolean add(String phone, String password, String nick) {
        // 用户的验证应该放到这里来，否则有安全问题
        User u = userMapper.loadByLoginname(phone);
        if (u != null) {
            if (!pwdEncoder.matches(password, u.getPassword())) {
                return false;
            }
        }
        User user = new User();
        user.setLoginname(phone);
        user.setPhone(phone);
        user.setRecommended(false);
        user.setPassword(pwdEncoder.encode(password));
        user.setNick(nick);
        //设置默认的用户名
        if (StringUtils.isEmpty(user.getNick())) {
            user.setNick(GlobalParam.USER_DEFAULT_NICK + UniqueIdGenerator.generateRandomNumStr(6));
        }
        //设置默认的个性签名
        if (StringUtils.isEmpty(user.getSignature())) {
            user.setSignature(GlobalParam.USER_DEFAULT_SIGNATURE);
        }
        this.insert(user);
        String qrcode = generateQrcode(user.getId());
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setQrcode(qrcode);
        updateUserInfo(userInfo, false);
        return true;
    }

    public String generateQrcode(String id) {
        /*String content ="http://m2.xunbaozl.com/userInfo.html?userId="+id;
		String key = qRCodeUtil.generateLogoQRCode(content).getKey();
		if( key != null ){
			return key;
		}*/
        return null;
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public boolean changePwd(String oldPwd, String newPwd, String userId) {
        User u = userQueryService.load(userId);
        //不传旧密码了，所有不用校验旧密码，但是看新旧密码是否一样
        if (SysStringUtils.isNotEmpty(u.getPassword())) {
            if (SysStringUtils.isNotBlank(newPwd) && pwdEncoder.matches(newPwd, u.getPassword())) {
                throw new BizException(GlobalErrorCode.UNKNOWN, "新密码和旧密码一样，请重新上传密码");
            }
        }
        if (!SysStringUtils.isEmpty(newPwd)) {
            newPwd = pwdEncoder.encode(newPwd);
            boolean changed = userMapper.changePwd(u.getId(), newPwd) > 0;
            return changed;
        }
        return false;
    }

    public boolean changePwd(String userId, String newPwd) {
        newPwd = pwdEncoder.encode(newPwd);
        boolean changed = userMapper.changePwd(userId, newPwd) > 0;
        return changed;
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public boolean updateUserInfo(User user, boolean checkNick) {
        if (checkNick && org.apache.commons.lang3.StringUtils.isNotEmpty(user.getNick())) {
            if (userStateService.userCountByNick(user.getNick(), user.getId()) > 0) {
                throw new BizException(GlobalErrorCode.UNKNOWN, "昵称已经存在");
            }
        }
        boolean isUpdated = false;
        if (user instanceof UserInfo) {
            isUpdated = userMapper.updateUserInfo((UserInfo) user) > 0;
        } else {
            isUpdated = userMapper.updateByPrimaryKeySelective(user) > 0;
        }
		
		/*if(isUpdated) {
			User oldUser = userMapper.selectByPrimaryKey(user.getId());
			try {
				SearchUser searchUser =  new SearchUser(IdTypeHandler.decode(oldUser.getId()),oldUser.getNick(),oldUser.getAvatar(),oldUser.getSignature());
				holder.update(searchUser);
			} catch (IOException e) {
				
			}
		}*/

        return isUpdated;
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public int delete(String id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public boolean emptyUserPassword(String mobile, String code) {
        // validate mobile and code
        User user = userMapper.loadByLoginname(mobile);
        if (user == null)
            return false;
        String userId = user.getId();
        return userMapper.emptyUserPassword(userId);
    }

    /**
     * 绑定用户账号
     *
     * @param
     * @author guohao
     * @date 2015年5月6日 下午1:32:03
     */
    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public User bindUser(BoundUserForm boundUserForm) {
        if (boundUserForm.getUserId() == null) {
            boundUserForm.setUserId(userTool.getCurrentUser().getId());
        }
        User user = userQueryService.load(boundUserForm.getUserId());
        if (user == null) {
            throw new BizException(GlobalErrorCode.UNKNOWN, "要绑定的用户不存在");
        }

        switch (boundUserForm.getAccountType()) {
            case LoginAccountType.QQ://绑定的QQ 账号
            case LoginAccountType.WEI_BO://绑定微博
            case LoginAccountType.WEI_XIN:
                ThirdUserServiceUtil.GetThirdUserService(boundUserForm.getAccountType()).boundUser(boundUserForm);
                break;
            case LoginAccountType.PHONE://绑定手机
                User u = userMapper.loadByPhone(boundUserForm.getPhone());
                if (u != null && !u.getId().equals(boundUserForm.getUserId())) {//如果此手机号已经存在了S
                    if (isFromWechat()) {//如果是微信端的账号
                        String openId = getCurrentOpenId();//BaseServiceImpl.getWechatOpenId();
                        UserWeixinOpenId userWeixinOpenId = userWeixinAccountMapper.loadByOpenId(openId);
                        userMapper.updateWeixinAccountUserId(u.getId(), userWeixinOpenId.getUnionId());
                        userWeixinAccountMapper.updateWeixinOpenIdAccountUserId(null, u.getId(), userWeixinOpenId.getUnionId());
                        return u;
                    } else {
                        // u.setLoginname(TokenProcessor.getInstance().generateToken(u.getPhone(),true));
                        //updateUserInfo(u,false);
                        //userMapper.setPhoneAndPasswdNull(u.getId());;

                        error("手机号已存在 ，不能再绑定");
                    }

                }
                user.setPhone(boundUserForm.getPhone());
                user.setLoginname(boundUserForm.getPhone());
                user.setPassword(pwdEncoder.encode(boundUserForm.getPwd()));
                userMapper.updateByPrimaryKeySelective(user);
                return user;

            default:
                break;
        }
        return null;
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public User registerBindUser(BoundUserForm boundUserForm) {
        User u = userMapper.loadByPhone(boundUserForm.getPhone());

        if (u != null) {
            String userId = userTool.getUserId();
            ThirdUserService service = ThirdUserServiceUtil.GetThirdUserService(boundUserForm.getAccountType());
            service.updateOpenId(userId);

            u.setPassword(pwdEncoder.encode(boundUserForm.getPwd()));
            userMapper.realDeleteById(userTool.getUserId());
            userMapper.updateByPrimaryKeySelective(u);
            return u;
        } else {
            User user = userMapper.selectByPrimaryKey(userTool.getUserId());
            user.setPhone(boundUserForm.getPhone());
            user.setLoginname(boundUserForm.getPhone());
            user.setPassword(pwdEncoder.encode(boundUserForm.getPwd()));
            userMapper.updateByPrimaryKeySelective(user);
            return user;
        }

    }

    /**
     * 解除账号绑定
     *
     * @param
     * @author guohao
     * @date 2015年5月7日 下午1:41:59
     */
    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public void unBindUser(String userId, Integer type) {

        ThirdUserService service = ThirdUserServiceUtil.GetThirdUserService(type);

        if (service != null) {
            service.unBoundUser(userId);
        }
    }

    /**
     * 根据关键字搜索
     *
     * @param
     * @author guohao
     * @date 2015年5月4日 上午11:37:12
     */
    @Override
    public List<UserInfo> searchUserKeywordAdept(String keyword, Pageable pageable) {
        UserInfo userInfo = new UserInfo();
        userInfo.setNick(keyword);
        List<String> ids = searchUtil.findIds(userInfo, pageable);
        if (ids.size() <= 0) new ArrayList<UserInfo>();
        List<UserInfo> userInfos = findSearchUsers(ids);
        //处理搜索出来的数据
        ArrayList<UserInfo> results = new ArrayList<UserInfo>();
        for (String id : ids) {
            UserInfo user = getUserinfo(userInfos, id);
            if (user != null) {
                results.add(user);
            }
        }
        return results;
    }

    private UserInfo getUserinfo(List<UserInfo> userInfos, String id) {

        for (UserInfo userInfo : userInfos) {
            if (userInfo.getId().equals(id)) {
                return userInfo;
            }
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    /**
     * 获取热门搜索用户
     *
     * @since 1.8.0
     */
    @Override
    public List<UserInfo> findHostSearchUsers(Pageable pager) {
        return userMapper.findHostSearchUsers(pager);
    }

    @Override
    public String getUserPhone(String userId) {
        return this.userMapper.getUserPhone(userId);
    }

    @Override
    public List<UserInfo> findSearchUsers(Collection<String> userIds) {
        if (userIds == null || userIds.size() <= 0) return new ArrayList<UserInfo>();

        return userMapper.findSearchUsers(userIds);
    }

    @Override
    public String loadQrcodeByUserId(String userId) {
        return userMapper.loadQrcodeByUserId(userId);
    }

    /* (non-Javadoc)
     * @see com.muying.service.user.UserService#loginByPhone(java.lang.String, java.lang.String)
     */
    @Override
    public User loginByPhone(String phone, String pwd) {
        User user = userMapper.loadByLoginname(phone);
        if (user != null) {
            if (pwdEncoder.matches(pwd, user.getPassword())) {
                user.getPassword();
                return user;
            }
            throw new BizException(GlobalErrorCode.UNKNOWN, "用户名或密码错误!");
        }
        return null;
    }

    @Override
    public List<User> findAllUser(Pageable pager) {

        return userMapper.findAllUser(pager);
    }

    @Override
    public long findAllUserCount() {
        return userMapper.findAllUserCount();
    }

    @Override
    public List<String> getUserIds(String nick) {
        return userMapper.getUserIds(nick);
    }


}
